//
//  QPJHInitNoticeView.m
//  QPJHInitNoticeView
//
//  Created by fish on 2021/9/8.
//  Copyright © 2021 Vanney. All rights reserved.
//

#import "QPJHInitNoticeView.h"
#import "QPJHFunDataFormat.h"
#import "QPConstHeader.h"
#import <WebKit/WebKit.h>

@interface QPJHInitNoticeView ()<WKUIDelegate, WKNavigationDelegate,UITextViewDelegate,WKScriptMessageHandler>

@property (nonatomic, strong) UIButton *coverView;
@property (nonatomic, strong) UIButton *closeBtn;
@property (nonatomic, strong) UIImageView *backBg;
//@property (nonatomic, strong) UIImageView *titleBg;
@property (nonatomic, strong) UILabel *titleLabel;
@property (strong, nonatomic) WKWebView *wkWebView;
@property (strong, nonatomic) UITextView *textView;
@property (strong, nonatomic) UITextView *keyTextView;
@property (copy, nonatomic) NSString *contentStr;
@property (copy, nonatomic) NSString *contentUrl;
@end

@implementation QPJHInitNoticeView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self drawIt];
    }
    return self;
}
- (void)drawIt {
    
    [self addSubview:self.backBg];

//    [self addSubview:self.titleBg];

    [self addSubview:self.closeBtn];
    
    [self addSubview:self.titleLabel];
    
    [self addSubview:self.textView];
    
    [self addSubview:self.keyTextView];
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.userContentController = [[WKUserContentController alloc] init];
    [config.userContentController addScriptMessageHandler:self name:@"eventComplete"];
    WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    self.wkWebView = wkWebView;
    if(@available(iOS 11.0, *)) {
        wkWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    wkWebView.UIDelegate = self;
    wkWebView.navigationDelegate = self;
    wkWebView.backgroundColor = [UIColor whiteColor];
    [self addSubview:wkWebView];
    
    if (IS_LANDSCAPE) {
        self.backBg.frame = UILanRectAdapter(0, 0, 400, 320);
        self.closeBtn.frame = UILanRectAdapter(125 , 260, 150 , 35);

        self.titleLabel.frame = UILanRectAdapter(0, 5, 400, 25);
        self.titleLabel.font = [UIFont boldSystemFontOfSize:20];
        
        self.textView.frame = UILanRectAdapter(20, 40, 400 - 40, 320 - 105);
        self.textView.font = [UIFont systemFontOfSize:16];
        
        self.wkWebView.frame = UILanRectAdapter(20, 40, 400 - 40, 320 - 105);
        
        self.keyTextView.frame = UILanRectAdapter(20, 40, 400 - 40, 320 - 105);
        self.keyTextView.font = [UIFont systemFontOfSize:16];
        
    } else {
        self.backBg.frame = UIPorRectAdapter(0, 0, 360, 360);
        self.closeBtn.frame = UIPorRectAdapter(105 , 300, 150 , 35);

        self.titleLabel.frame = UIPorRectAdapter(0, 5, 360, 25);
        self.titleLabel.font = [UIFont boldSystemFontOfSize:20];
        
        self.textView.frame = UIPorRectAdapter(20, 42, 360 - 40, 360 - 105);
        self.textView.font = [UIFont systemFontOfSize:16];

        self.textView.frame = UIPorRectAdapter(20, 42, 360 - 40, 360 - 105);

        self.keyTextView.frame = UIPorRectAdapter(20, 42, 360 - 40, 360 - 105);
        self.keyTextView.font = [UIFont systemFontOfSize:16];
    }
//    self.textView.text = @"在游戏中主动退出SDK, 或者在悬浮窗中切换账号 都会走此回调, 请在此方法中做游戏退出的操作。请勿在此方法中调用我方退出接口, 否则会导致死循环";
   
}
- (void)binData:(NSDictionary *)dic {
    NSString *notice_url = [NSString stringWithFormat:@"%@",dic[@"data"][@"notice_data"][@"notice_url"]];
    NSString *notice_title = [NSString stringWithFormat:@"%@",dic[@"data"][@"notice_data"][@"notice_title"]];
    NSString *notice_type = [NSString stringWithFormat:@"%@",dic[@"data"][@"notice_data"][@"notice_type"]];
    NSString *notice_content = [NSString stringWithFormat:@"%@",dic[@"data"][@"notice_data"][@"notice_content"]];
    self.titleLabel.text = notice_title;
    
    self.textView.hidden = YES;
    self.wkWebView.hidden = YES;
    self.keyTextView.hidden = YES;
    
    if ([notice_type isEqualToString:@"1"]) {
        self.textView.hidden = NO;
        self.textView.text = notice_content;

    } else if ([notice_type isEqualToString:@"2"]) {
        self.wkWebView.hidden = NO;
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:notice_url]];
        [self.wkWebView loadRequest:request];
    } else if ([notice_type isEqualToString:@"3"]) {
        self.keyTextView.hidden = NO;
        NSDictionary *dic = [QPJHFunDataFormat dictionaryWithJsonString:notice_url];
        NSString *content = [NSString stringWithFormat:@"%@",dic[@"content"]];
        NSString *url_content = [NSString stringWithFormat:@"%@",dic[@"url_content"]];
        NSString *url = [NSString stringWithFormat:@"%@",dic[@"url"]];
        self.contentStr = url_content;
        self.contentUrl = url;
        self.keyTextView.text = [NSString stringWithFormat:@"%@%@",content,url_content];
        NSRange range = [self.keyTextView.text rangeOfString:url_content];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.keyTextView.text];
        [attributedString addAttribute:NSLinkAttributeName
                                 value:@"wenzilianjie://"
                                 range:[[attributedString string] rangeOfString:url_content]];
        [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, attributedString.length)];
        
        [attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:range];
        self.keyTextView.attributedText = attributedString;
        self.keyTextView.textColor = [UIColor colorWithRed:152/255.0 green:113/255.0 blue:91/255.0 alpha:1.0];

        self.keyTextView.linkTextAttributes = @{NSForegroundColorAttributeName: [UIColor colorWithRed:(33)/255.0f green:(175)/255.0f blue:(215)/255.0f alpha:1] };
        self.keyTextView.editable = NO;
        self.keyTextView.scrollEnabled = NO;
        self.keyTextView.selectable = NO;
        self.keyTextView.delegate = self;
        UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addGestureRecognizer:)];
        [self.keyTextView addGestureRecognizer:tapRecognizer];
        
    }
}
- (void)addGestureRecognizer:(UIGestureRecognizer*)gestureRecognizer {
    if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]])
    {
        CGPoint tapLocation = [gestureRecognizer locationInView:self.keyTextView];
        UITextPosition *textPosition = [self.keyTextView closestPositionToPoint:tapLocation];
        NSDictionary *attributes = [self.keyTextView textStylingAtPosition:textPosition inDirection:UITextStorageDirectionBackward];
        NSURL *url = attributes[NSLinkAttributeName];
        if(url) {
            NSRange range = [self.keyTextView.text rangeOfString:self.contentStr];

            [self  textView:self.keyTextView shouldInteractWithURL:[NSURL URLWithString:self.contentUrl] inRange:range];
            
        }
        
    }
    [super addGestureRecognizer:gestureRecognizer];
}
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
    [[UIApplication sharedApplication] openURL:URL];
    
    return YES;
}
- (void)show {
    UIButton *coverView = [[UIButton alloc] init];
    coverView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3f];
    self.coverView = coverView;

    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    coverView.frame = window.bounds;
    
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *visualView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    visualView.alpha = 0.5;
    [coverView addSubview:visualView];
    visualView.frame = coverView.frame;
    
    [window addSubview:coverView];
    
    self.frame = IS_LANDSCAPE ? UILanRectAdapter(0, 0, 400, 320): UIPorRectAdapter(0, 0, 360, 360);
    self.center = window.center;
    [window addSubview:self];
}
- (void)dissmiss {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.coverView removeFromSuperview];
        [self.closeBtn removeFromSuperview];
        [self removeFromSuperview];
        if (self.closeBlock) {
            self.closeBlock();
        }
    });
}

#pragma mark - 页面加载完后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
}
#pragma mark - 加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
}
#pragma mark - web界面中有弹出警告框时调用
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
        completionHandler(YES);
}
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {

    completionHandler();
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler{

}
#pragma mark - 从web界面中接收到一个脚本时调用
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if([message.name isEqualToString:@"eventComplete"]) {
        NSString *bodyDataStr = [NSString stringWithFormat:@"%@",message.body];
        
        NSDictionary *params = [QPJHFunDataFormat dictionaryWithJsonString:bodyDataStr];
        
        NSString *action = [NSString stringWithFormat:@"%@",[params objectForKey:@"action"]];
        NSDictionary *dic = [QPJHFunDataFormat dictionaryWithJsonString:[params objectForKey:@"data"]];
        NSString *link = [NSString stringWithFormat:@"%@",dic[@"link"]];
//        NSLog(@"function=%@ ",link);

         if ([action isEqualToString:@"openurl"]) {
             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:link]];
        }
        
    }
}
- (UIImageView *)backBg {
    if (_backBg == nil) {
        _backBg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"QPFUNSDK.bundle/portrait/bg_init"]];
        _backBg.userInteractionEnabled = YES;
    }
    return _backBg;
}
//- (UIImageView *)titleBg {
//    if (_titleBg == nil) {
//        _titleBg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"QPFUNSDK.bundle/gifts/bg_notice_title"]];
//    }
//    return _titleBg;
//}
- (UIButton *)closeBtn {
    if (_closeBtn == nil) {
        _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeBtn addTarget:self action:@selector(dissmiss) forControlEvents:UIControlEventTouchUpInside];
        [_closeBtn setBackgroundImage:[UIImage imageNamed:@"QPFUNSDK.bundle/portrait/bg_sure"] forState:UIControlStateNormal];
    }
    return _closeBtn;
}
- (UILabel *)titleLabel {
    if (_titleLabel == nil) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.numberOfLines = 0;
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
//        _titleLabel.font = [UIFont fontWithName:QPFONTCuYuan size:UILanAdapter(15)];
    }
    return _titleLabel;
}
- (UITextView *)textView {
    if (_textView == nil) {
        _textView = [UITextView new];
        _textView.backgroundColor = UIColor.clearColor;
        _textView.font = [UIFont systemFontOfSize:15];//[UIFont fontWithName:QPFONTLTKHGBK size:UILanAdapter(15)];
        _textView.textColor = [UIColor colorWithRed:130/255.0 green:89/255.0 blue:73/255.0 alpha:1.0];
        _textView.textAlignment = NSTextAlignmentLeft;
        _textView.editable = NO;
    }
    return _textView;
}
- (UITextView *)keyTextView {
    if (_keyTextView == nil) {
        _keyTextView = [UITextView new];
        _keyTextView.backgroundColor = UIColor.clearColor;
        _keyTextView.font = [UIFont systemFontOfSize:15];//[UIFont fontWithName:QPFONTLTKHGBK size:UILanAdapter(15)];
        _keyTextView.textColor = [UIColor colorWithRed:152/255.0 green:113/255.0 blue:91/255.0 alpha:1.0];
        _keyTextView.textAlignment = NSTextAlignmentLeft;
        _keyTextView.editable = NO;
    }
    return _keyTextView;
}

@end
